package com.stadyhelper.contreller;

import com.stadyhelper.Utils.JwtUtil;
import com.stadyhelper.Utils.Md5Util;
import com.stadyhelper.Utils.ThreadLocalUtil;
import com.stadyhelper.pojo.Result;
import com.stadyhelper.pojo.User;
import com.stadyhelper.service.UserService;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@RequestParam @Pattern(regexp = "^\\S{5,16}$") String username,
                           @RequestParam @Pattern(regexp = "^\\S{5,16}$")String password) {
        User user = userService.findByUsername(username);
        if(user == null) {
            userService.register(username,password);
            return Result.success();
        }else {
            return Result.error("用户名已存在！");
        }
    }

    @PostMapping("/login")
    public Result login(@RequestParam @Pattern(regexp = "^\\S{5,16}$") String username,
                        @RequestParam @Pattern(regexp = "^\\S{5,16}$")String password) {
        User user = userService.findByUsername(username);
        if(user == null) {
            return Result.error("用户不存在！");
        }
        if(Md5Util.getMD5String(password).equals(user.getPassword())) {
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            String token=JwtUtil.genToken(claims);
            //把token存入redis
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            ops.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误！");
    }
    //根据username查询
    @GetMapping("/user/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token) {
        /*Map<String,Object> claims = JwtUtil.parseToken(token);
        String username = (String) claims.get("username");*/
        Map<String,Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        return Result.success(userService.findByUsername(username));
    }
    //更新user
    @PutMapping("/user/update")
    //@RequestBody将JOSN数据转换为实体对象
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }
    //更新密码
    @PatchMapping("/user/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> map ,@RequestHeader("Authorization") String token) {
        //判断参数
        //不为空
        if(!StringUtils.hasLength(map.get("old_pwd")) || !StringUtils.hasLength(map.get("new_pwd")) || !StringUtils.hasLength(map.get("re_pwd"))) {
            return Result.error("缺少必要参数！");
        }
        //重输密码相等
        if(!map.get("new_pwd").equals(map.get("re_pwd"))) {
            return Result.error("两次密码不相同!");
        }
        //调用方法更新
        userService.updatePwd(map.get("new_pwd"));
        //更新后删除redis中对应旧token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        return Result.success();
    }
    @GetMapping("/user/goods")
    public Result<List<User>> list(){
        return Result.success(userService.selectAll());
    }
}
